import {action, observable} from "mobx-miniprogram"
export const store=observable({
  numA:1,
  numB:2,
  userinfo: JSON.parse(uni.getStorageSync('userinfo') || '{}'),
  address: JSON.parse(wx.getStorageSync('address')||'[]'),
  cart:JSON.parse(wx.getStorageSync('cart')||'[]'),
  updateAddress:action(function(address){
    this.address=address
    wx.setStorageSync('address',this.address)
  }),
  update:action(function (){
    this.numA+=1
    this.numB+=1
  }),
  updatecart: action (function (str){
    this.cart.push(...str)
  }),
  addToCart:action(function(goods) {
    // 根据提交的商品的Id，查询购物车中是否存在这件商品
    // 如果不存在，则 findResult 为 undefined；否则，为查找到的商品信息对象
    const findResult = this.cart.find((x) => x.goods_id === goods.goods_id)

    if (!findResult) {
      // 如果购物车中没有这件商品，则直接 push
      this.cart.push(goods)
    } else {
      // 如果购物车中有这件商品，则只更新数量即可
      findResult.goods_count++
    }
    return this.cart
  }),
  addNumber: action(function(index,symbol){
    console.log("store进来")
    // console.log(this.cart)
    if(symbol==0)
    {
      if(  this.cart[index].goods_count!=1)
      this.cart[index].goods_count--
    }
    else
    this.cart[index].goods_count++
    wx.setStorageSync('cart', JSON.stringify(this.cart))
  }),
  delecate:action(function(index){
    this.cart.splice(index,1)
    wx.setStorageSync('cart', JSON.stringify(this.cart))
  }),
  select:action(function(index){
    this.cart[index].goods_state=! this.cart[index].goods_state
    wx.setStorageSync('cart', JSON.stringify(this.cart))
  }),
  Alldelete:action(function(){
    wx.removeStorageSync('cart')
    this.cart=JSON.parse(wx.getStorageSync('cart')||'[]')
  }),
  get number(){
    var money=0
    for (let index = 0; index < this.cart.length; index++) {
     if(this.cart[index].goods_state==true)
          money=money+this.cart[index].goods_price*this.cart[index].goods_count
    }
    return money
  },
  get sum(){
    return this.numA+this.numB
  }
})